require 'rss'
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time

  # See ActionController::RequestForgeryProtection for details
  # Uncomment the :secret if you're not using the cookie session store
  protect_from_forgery # :secret => '65a73a11695df842eed9f12ff6df62f4'
  
  # See ActionController::Base for details 
  # Uncomment this to filter the contents of submitted sensitive data parameters
  # from your application log (in this case, all fields with names like "password"). 
  # filter_parameter_logging :password

  before_filter :authenticate_member, :except => ['index']
  ::ROOTS_CATEGORIES = Category.find_all_by_category_id(nil, :order => 'label ASC')
  ::SVNCHANGES_FEED = RSS::Parser.parse('http://code.google.com/feeds/p/hellaworld-rev/svnchanges/basic')
  def authenticate_member
    if(session[:user] && session[:user].id)
      return true
    else
      redirect_to '/'
    end
  end
  
  def authenticate_admin
    if(session[:user] && session[:user].rights>=ADMIN_USER)
      return true
    else
      redirect_to '/'
    end
  end
  
  def index
    if session[:user]
      @comment = Comment.new
      @last_comments = Comment.find(:all, :order => 'created_at DESC', :limit => 50)
      @top_zeudou_medias = Media.find(:all, :conditions => "local_path != \"\"", :order => 'score DESC,  updated_at DESC', :limit => 12)
      @top_louze_medias = Media.find(:all, :conditions => "local_path != \"\"", :order => 'score ASC, updated_at ASC', :limit => 12)
      render :template => 'application/member_index'
    end
  end

  def hella_status
    if Hellanzb.instance.is_connected?
      render :partial => 'application/adv_status'
    else
      render :text => "hellanzb daemon stopped"
    end
  end

  def sanitize_filename(path)
	  if RUBY_PLATFORM =~ %r{unix|linux|solaris|freebsd}
        path.gsub!(/[^\w\.\-]/, '_')
	  elsif RUBY_PLATFORM =~ %r{win32}
	    # Replace illegal characters for NTFS with _
	    path.gsub!(/[\x00-\x1f\/|?*]/,'_')
	  else
	    # Assume a very restrictive OS such as MSDOS
	    path.gsub!(/[\/|\?*+\]\[ \x00-\x1fa-z]/,'_')
	  end

	  # For files uploaded by Windows users, strip off the beginning path.
	  return path.gsub(/^.*[\\\/]/, '')
  end

  def start_hellanzb
    Hellanzb.instance.connect_hellanzb
    redirect_to '/'
  end

  def stop_hellanzb
     Hellanzb.instance.disconnect_hellanzb
     redirect_to '/'
  end

  def continue_hellanzb
     Hellanzb.instance.continue
     redirect_to '/'
  end
end
